package com.example.nutrition;


import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class DataSource {

	private SQLiteDatabase database;
	private MySQLiteHelper dbHelper;
	private String[] allColums = {"ID", "Name", "kcal", "Magnesium","Calcium","Eisen","Zink"};
	
	/*
	 * private static final String TABLE_CREATE_LEBENSMITTEL = ""
			+ "create table Lebensmittel("
			+ " ID integer primary key autoincrement," + "Name text, "
			+ "kcal int," + "Magnesium int,"+"'Calcium int,"+"Eisen int,"+"Zink int)";

	;
	 */
	
	public DataSource(Context context){
		dbHelper = new MySQLiteHelper(context);
	}
	
	public void open() throws SQLException{
		database = dbHelper.getWritableDatabase();
	}
	
	public void close(){
		dbHelper.close();
	}
	
	public Lebensmittel createLebensmittel(String name, int kcal, double Magnesium, double Calcium, double Eisen, double Zink){
		ContentValues values = new ContentValues();
		values.put("Name", name);
		values.put("kcal", kcal);
		values.put("Magnesium", Magnesium);
		values.put("Calcium", Calcium);
		values.put("Eisen", Eisen);
		values.put("Zink", Zink);
		
		long insertId = database.insert("Lebensmittel", null, values);
		
		Cursor cursor = database.query("Lebensmittel", allColums, "ID = " + insertId, null, null, null, null);
		cursor.moveToFirst();
		
		return cursorToLebensmittel(cursor);
	}
	
	private Lebensmittel cursorToLebensmittel(Cursor cursor){
		Lebensmittel lebensmittel = new Lebensmittel();
		lebensmittel.setId(cursor.getLong(0));
		lebensmittel.setName(cursor.getString(1));
		lebensmittel.setKcal(cursor.getInt(2));
		lebensmittel.setMagnesium(cursor.getDouble(3));
		lebensmittel.setCalcium(cursor.getDouble(4));
		lebensmittel.setEisen(cursor.getDouble(5));
		lebensmittel.setZink(cursor.getDouble(6));
		
		return lebensmittel;
	}
	

	
	protected List<Lebensmittel> getAllLebensmittel(){
		List<Lebensmittel> List_Lebensmittel = new ArrayList<Lebensmittel>();
		
		Cursor cursor = database.query("Lebensmittel", allColums, null, null, null, null, null);
		cursor.moveToFirst();
		
		if(cursor.getCount() == 0){
			return List_Lebensmittel;
		}
		
		while(cursor.isAfterLast() == false){
			Lebensmittel lebensmittel = cursorToLebensmittel(cursor);
			List_Lebensmittel.add(lebensmittel);
			cursor.moveToNext();
		}
		
		cursor.close();
		
		return List_Lebensmittel;
		
	}
	
	
	
}
